from rest_framework import serializers
from goods.models import SKU
from drf_haystack.serializers import HaystackSerializer

from goods.search_indexes import SKUIndex
from  django_redis import  get_redis_connection

class GoodsSerializers(serializers.ModelSerializer):
    class Meta:
        model = SKU

        fields = '__all__'


# 创建haystack序列化器
class SKUIndexSerializers(HaystackSerializer):
    # 返回的商品数据对象指定返回的字段内容
    object = GoodsSerializers(read_only=True)

    class Meta:
        index_classes = [SKUIndex]  # 指定索引类
        fields = ('text', 'object')


# 定义获取用户浏览商品的序列器
class GoodsHistorySerializers(serializers.Serializer):
    # 获取商品
    sku_id = serializers.IntegerField(label="商品SKU编号", min_value=1)

    # 验证sku_id对应的商品是否存在
    def validated_sku_id(self,value):
        try:
            SKU.objects.get(id=value)
        except:
            raise  serializers.ValidationError('该商品不存在')

        return  value

    # 保存数据
    def create(self, validated_data):
        sku_id=validated_data['sku_id']
        user_id=self.context['request'].user.id

        # 数据保存到redis中
        redis_conn=get_redis_connection('history')
        pl=redis_conn.pipeline()

        # 删除已经存在的本商品的数据
        pl.lrem('history_%s'%user_id,0,sku_id)
        # 添加新浏览的记录
        pl.lpush('history_%s'%user_id,sku_id)
        # 保存5条浏览记录
        pl.ltrim('history_%s'%user_id,0,4)

        pl.execute()

        return  validated_data